package com.c4p.controller;


import com.alibaba.fastjson2.JSONObject;
import com.c4p.clazz.CompilingClassLoader;
import com.c4p.match.IMatch;
import com.c4p.device.Bms;
import com.c4p.store.IStore;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@Slf4j
public class GenController {

    @Autowired
    CompilingClassLoader compilingClassLoader;
    @Autowired
    IStore store;


    @PostMapping("/gen")
    public Mono<String> gen(@RequestBody ReqGen req) throws Exception{
        log.info("gen request -> {}", req);
        String clazzName = req.getClazzName();
        //编译对象
        byte[] byteArray = compilingClassLoader.compiling(
                clazzName, req.getClazzStr(), null);

        JSONObject clazzCompiled = new JSONObject();
        clazzCompiled.put("clazzName", clazzName);
        clazzCompiled.put("clazzCode", byteArray);
        store.put(req.getTitle(), clazzCompiled);

        return Mono.just("succeed");
    }

    @PostMapping("/load")
    public Mono<String> load(@RequestBody ReqLoad req) throws Exception{
        log.info("load request -> {}", req);
        JSONObject jsonObject = (JSONObject) store.get(req.getTitle());
        log.info("从redis加载class -> {}" , jsonObject);
        Class<?> defineClass = compilingClassLoader.defineClass(
                jsonObject.getString("clazzName"), jsonObject.getBytes("clazzCode"));

        IMatch instance = (IMatch) defineClass.newInstance();
        Bms bms = new Bms();
        bms.setWd(req.getMatch());
        log.info("bool = {}", instance.match(bms));

        return Mono.just("succeed");
    }


    @Data
    @NoArgsConstructor
    static class ReqGen {
        private String title;
        private String clazzName;
        private String clazzStr;
    }

    @Data
    @NoArgsConstructor
    static class ReqLoad{
        private String title;
        private String match;
    }
}
